import React from 'react';
// import SearchIcon from '@material-ui/icons/Search';
import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';
import ArrowDownwardIcon from '@mui/icons-material/ArrowDownward';
import DeleteIcon from '@mui/icons-material/Delete';
import FlipIcon from '@mui/icons-material/Flip';
import DropdownButton from './DropdownButton';
import MenuItem from '@mui/material/MenuItem';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Colors from './Colors';

import { fabric } from "fabric";

console.log(fabric);
let canvas;
// var tshirts = new Array(); //prototype: [{style:'x',color:'white',front:'a',back:'b',price:{tshirt:'12.95',frontPrint:'4.99',backPrint:'4.99',total:'22.47'}}]
var a;
var b;
var line1;
var line2;
var line3;
var line4;
function getRandomNum(min, max) {
  return Math.random() * (max - min) + min;
}
let _ = require('lodash');
let fs, path, ipcRenderer;
if (window.require) {
  fs = window.require('fs');
  path = window.require('path');
  ipcRenderer = window.require('electron').ipcRenderer; //
}

export default class A4Lian extends React.Component {
  img_click = e => {
    var el = e.target;
    /*temp code*/
    var offset = 50;
    var left = fabric.util.getRandomInt(0 + offset, 200 - offset);
    var top = fabric.util.getRandomInt(0 + offset, 400 - offset);
    var angle = fabric.util.getRandomInt(-20, 40);
    var width = fabric.util.getRandomInt(30, 50);
    var opacity = (function(min, max) {
      return Math.random() * (max - min) + min;
    })(0.5, 1);

    fabric.Image.fromURL(el.src, function(image) {
      image.set({
        left: left,
        top: top,
        angle: 0,
        padding: 10,
        cornersize: 10,
        hasRotatingPoint: true,
      });
      //image.scale(getRandomNum(0.1, 0.25)).setCoords();
      canvas.add(image);
    });
    this.setState({
      display_imageEditor: 'block',
    });
  };
  delete_selected = () => {
    var activeObject = canvas.getActiveObject();
    // activeGroup = canvas.getActiveGroup();
    if (activeObject) {
      canvas.remove(activeObject);
      // $("#text-string").val("");
      this.setState({ text: '' });
    }
    // else if (activeGroup) {
    //   var objectsInGroup = activeGroup.getObjects();
    //   canvas.discardActiveGroup();
    //   objectsInGroup.forEach(function(object) {
    //     canvas.remove(object);
    //   });
    // }
  };
  text_change = e => {
    this.setState({ text: e.target.value });
  };
  Bold_click = () => {
    var activeObject = canvas.getActiveObject();
    if (activeObject && activeObject.type === 'text') {
      activeObject.fontWeight = activeObject.fontWeight == 'bold' ? '' : 'bold';
      canvas.renderAll();
    }
  };
  Italic_click = () => {
    var activeObject = canvas.getActiveObject();
    if (activeObject && activeObject.type === 'text') {
      activeObject.fontStyle =
        activeObject.fontStyle == 'italic' ? '' : 'italic';
      canvas.renderAll();
    }
  };
  Strike_click = () => {
    var activeObject = canvas.getActiveObject();
    if (activeObject && activeObject.type === 'text') {
      activeObject.textDecoration =
        activeObject.textDecoration == 'line-through' ? '' : 'line-through';
      canvas.renderAll();
    }
  };
  Underline_click = () => {
    var activeObject = canvas.getActiveObject();
    window.a=activeObject;
    if (activeObject && activeObject.type === 'text') {
      activeObject.underline = !activeObject.underline
      canvas.renderAll();
    }
  };
  text_fontcolor_change = e => {
    this.setState({ text_fontcolor: e.target.value });
    var activeObject = canvas.getActiveObject();
    if (activeObject && activeObject.type === 'text') {
      activeObject.fill = e.target.value;
      canvas.renderAll();
    }
  };
  text_strokecolor_change = e => {
    this.setState({ text_strokecolor: e.target.value });
    var activeObject = canvas.getActiveObject();
    if (activeObject && activeObject.type === 'text') {
      activeObject.strokeStyle = e.target.value;
      canvas.renderAll();
    }
  };
  addText = () => {
    var text = this.state.text;
    var textSample = new fabric.Text(text, {
      left: fabric.util.getRandomInt(0, 200),
      top: fabric.util.getRandomInt(0, 400),
      fontFamily: 'helvetica',
      angle: 0,
      fill: '#000000',
      scaleX: 0.5,
      scaleY: 0.5,
      fontWeight: '',
      hasRotatingPoint: true,
    });
    canvas.add(textSample);
    canvas.item(canvas.item.length - 1).hasRotatingPoint = true;
    this.setState({
      display_imageEditor: 'block',
      display_texteditor: 'flex',
    });
  };
  upward=()=>{
    var activeObject = canvas.getActiveObject()
    if (activeObject) {
      activeObject.bringToFront();
    } 
  }
  downward=()=>{
   
   var activeObject = canvas.getActiveObject();
    if (activeObject) {
      activeObject.sendToBack();
    }
  }
  flip=()=>{
    if ($(this).attr('data-original-title') == 'Show Back View') {
      $(this).attr('data-original-title', 'Show Front View');
      $('#tshirtFacing').attr('src', 'img/crew_back.png');
      a = JSON.stringify(canvas);
      canvas.clear();
      try {
        var json = JSON.parse(b);
        canvas.loadFromJSON(b);
      } catch (e) {}
    } else {
      $(this).attr('data-original-title', 'Show Back View');
      $('#tshirtFacing').attr('src', 'img/crew_front.png');
      b = JSON.stringify(canvas);
      canvas.clear();
      try {
        var json = JSON.parse(a);
        canvas.loadFromJSON(a);
      } catch (e) {}
    }
    canvas.renderAll();
    setTimeout(function() {
      canvas.calcOffset();
    }, 200);
  }
  onMouseEnter = () => {
    // console.log('onMouseEnter');
    // console.log(line1);
    canvas.add(line1);
    canvas.add(line2);
    canvas.add(line3);
    canvas.add(line4);
    canvas.renderAll();
  };
  onMouseLeave = () => {
    // console.log('onMouseLeave');
    canvas.remove(line1);
    canvas.remove(line2);
    canvas.remove(line3);
    canvas.remove(line4);
    canvas.renderAll();
  };
  color_click = e => {
    // console.log(e.target.style.backgroundColor);
    // window.s=e.target.style.backgroundColor
    this.setState({ color: e.target.style.backgroundColor });
  };
  removeWhite = () => {
    var activeObject = canvas.getActiveObject();
    if (activeObject && activeObject.type === 'image') {
      activeObject.filters[2] = new fabric.Image.filters.RemoveWhite({
        hreshold: 100,
        distance: 10,
      }); //0-255, 0-255
      activeObject.applyFilters(canvas.renderAll.bind(canvas));
    }
  };
  setFont = font => {
    var activeObject = canvas.getActiveObject();
    if (activeObject && activeObject.type === 'text') {
      activeObject.fontFamily = font;
      canvas.renderAll();
    }
  };
  constructor() {
    super();
    this.state = { value: 0 };
    this.state.color = 'rgb(255, 255, 255)';
    this.state.text = '';
    this.state.display_texteditor = 'none';
    this.state.display_imageEditor = 'none';
    this.state.text_fontcolor = '#000000';
    this.state.text_strokecolor = '#000000';
  }
  handleChange = (event, value) => {
    this.setState({ value });
  };
  componentWillUnmount = () => {};
  onObjectSelected = e => {
    console.log("onObjectSelected")
    var selectedObject = e.target;
    if(!selectedObject) return;
    // $("#text-string").val("");
    this.setState({ text: '' });
    selectedObject.hasRotatingPoint = true;
    console.log(selectedObject);
    if (selectedObject && selectedObject.type === 'text') {
      //display text editor
      // $("#texteditor").css('display', 'block');
      this.setState({ display_texteditor: 'block' });
      // $("#text-string").val(selectedObject.getText());
      this.setState({ text: selectedObject.text });
      // $('#text-fontcolor').miniColors('value',selectedObject.fill);
      // $('#text-strokecolor').miniColors('value',selectedObject.strokeStyle);
      // $("#imageeditor").css('display', 'block');
      this.setState({ display_imageEditor: 'none' });
    } else if (selectedObject && selectedObject.type === 'image') {
      //display image editor
      this.setState({ display_imageEditor: 'block' });
      this.setState({ display_texteditor: 'none' });
    }
  };
  onSelectedCleared = e => {
    this.setState({ display_texteditor: 'none' });
    this.setState({ text: '' });
    this.setState({ display_imageEditor: 'none' });
  };
  componentDidMount = () => {
    canvas = new fabric.Canvas('tcanvas', {
      width: 200,
      height: 400,
      hoverCursor: 'pointer',
      selection: true,
      selectionBorderColor: 'blue',
    });
    window.canvas=canvas
    canvas.on({
      'object:moving': function(e) {
        e.target.opacity = 0.5;
      },
      'object:modified': function(e) {
        e.target.opacity = 1;
      },
      'selection:created': this.onObjectSelected,
      'selection:updated': this.onObjectSelected,
      'selection:cleared': this.onSelectedCleared,
    });
    // piggyback on `canvas.findTarget`, to fire "object:over" and "object:out" events
    canvas.findTarget = (function(originalFn) {
      return function() {
        var target = originalFn.apply(this, arguments);
        if (target) {
          if (this._hoveredTarget !== target) {
            canvas.fire('object:over', { target: target });
            if (this._hoveredTarget) {
              canvas.fire('object:out', { target: this._hoveredTarget });
            }
            this._hoveredTarget = target;
          }
        } else if (this._hoveredTarget) {
          canvas.fire('object:out', { target: this._hoveredTarget });
          this._hoveredTarget = null;
        }
        return target;
      };
    })(canvas.findTarget);

    // canvas.on('object:over', function(e) {
    //   e.target.fill='red';
    //   canvas.renderAll();
    // });

    // canvas.on('object:out', function(e) {
    //   e.target.fill='green';
    //   canvas.renderAll();
    // });
    line1 = new fabric.Line([0, 0, 200, 0], {
      stroke: '#000000',
      strokeWidth: 1,
      hasBorders: false,
      hasControls: false,
      hasRotatingPoint: false,
      selectable: false,
    });
    line2 = new fabric.Line([199, 0, 200, 399], {
      stroke: '#000000',
      strokeWidth: 1,
      hasBorders: false,
      hasControls: false,
      hasRotatingPoint: false,
      selectable: false,
    });
    line3 = new fabric.Line([0, 0, 0, 400], {
      stroke: '#000000',
      strokeWidth: 1,
      hasBorders: false,
      hasControls: false,
      hasRotatingPoint: false,
      selectable: false,
    });
    line4 = new fabric.Line([0, 400, 200, 399], {
      stroke: '#000000',
      strokeWidth: 1,
      hasBorders: false,
      hasControls: false,
      hasRotatingPoint: false,
      selectable: false,
    });
  };
  render() {
    return (
      <div style={{ display: 'flex' }}>
        <div>
          <Tabs
            ref="tabList"
            value={this.state.value}
            onChange={this.handleChange}
          >
            <Tab label="T-Shirt Options" />
            <Tab label="Gravatar" />
          </Tabs>
          {this.state.value === 0 && (
            <div>
              <div
                style={{
                  width: '250px',
                  height: '100vh',
                  border: 'solid 1px black',
                }}
              >
                <select id="" value="1" onChange={() => {}}>
                  <option value="1">Short Sleeve Shirts</option>
                  <option value="2">Long Sleeve Shirts</option>
                  <option value="3">Hoodies</option>
                  <option value="4">Tank tops</option>
                </select>
                <Colors color_click={this.color_click} />
              </div>
            </div>
          )}
          {this.state.value === 1 && (
            <div>
              <div
                style={{
                  width: '250px',
                  height: '100vh',
                  border: 'solid 1px black',
                }}
              >
                <div className="input-append">
                  <input
                    className="span2"
                    id="text-string"
                    type="text"
                    value={this.state.text}
                    onChange={this.text_change}
                    placeholder="add text here..."
                  />
                  <button
                    id="add-text"
                    onClick={this.addText}
                    className="btn"
                    title="Add text"
                  >
                    add
                  </button>
                  <hr />
                </div>
                <div id="avatarlist">
                  <img
                    style={{ cursor: 'pointer' }}
                    className="img-polaroid"
                    onClick={this.img_click}
                    src="./Title_files/invisibleman.jpg"
                  />
                  <img
                    onClick={this.img_click}
                    style={{ cursor: 'pointer' }}
                    className="img-polaroid"
                    src="./Title_files/arrow.png"
                  />
                  <img
                    onClick={this.img_click}
                    style={{ cursor: 'pointer' }}
                    className="img-polaroid"
                    src="./Title_files/rect.png"
                  />
                  <img
                    onClick={this.img_click}
                    style={{ cursor: 'pointer' }}
                    className="img-polaroid"
                    src="./Title_files/circle.png"
                  />
                  <img
                    onClick={this.img_click}
                    style={{ cursor: 'pointer' }}
                    className="img-polaroid"
                    src="./Title_files/ling.png"
                  />
                  <img
                    onClick={this.img_click}
                    style={{ cursor: 'pointer' }}
                    className="img-polaroid"
                    src="./Title_files/rect.png"
                  />
                </div>
              </div>
            </div>
          )}
        </div>
        <div>
          <div align="center" style={{ minHeight: '32px' }}>
            <div>
              <div
                id="texteditor"
                style={{ display: this.state.display_texteditor }}
              >
                <DropdownButton title="font">
                  <MenuItem
                    onClick={() => {
                      this.setFont('Arial');
                    }}
                  >
                    Arial
                  </MenuItem>
                  <MenuItem
                    onClick={() => {
                      this.setFont('Helvetica');
                    }}
                  >
                    Helvetica
                  </MenuItem>
                  <MenuItem
                    onClick={() => {
                      this.setFont('Monaco');
                    }}
                  >
                    Monaco
                  </MenuItem>
                  {
                    // Helvetica
                    // Myriad Pro
                    // Delicious
                    // Verdana
                    // Georgia
                    // Courier
                    // Comic Sans MS
                    // Impact
                    // Monaco
                    // Optima
                    // Hoefler Text
                    // Plaster
                    // Engagement
                  }
                </DropdownButton>
                <button
                  id="text-bold"
                  className="btn"
                  onClick={this.Bold_click}
                  data-original-title="Bold"
                >
                  <img src="./Title_files/font_bold.png" height="" width="" />
                </button>
                <button
                  id="text-italic"
                  className="btn"
                  data-original-title="Italic"
                  onClick={this.Italic_click}
                >
                  <img src="./Title_files/font_italic.png" height="" width="" />
                </button>
                <button
                  id="text-strike"
                  className="btn"
                  title="Strike"
                  onClick={this.Strike_click}
                >
                  <img
                    src="./Title_files/font_strikethrough.png"
                    height=""
                    width=""
                  />
                </button>
                <button
                  id="text-underline"
                  className="btn"
                  title="Underline"
                  onClick={this.Underline_click}
                >
                  <img src="./Title_files/font_underline.png" />
                </button>
                <input
                  id="text-fontcolor"
                  type="color"
                  size="7"
                  value={this.state.text_fontcolor}
                  onChange={this.text_fontcolor_change}
                />
                <input
                  id="text-strokecolor"
                  type="color"
                  size="7"
                  value={this.state.text_strokecolor}
                  onChange={this.text_strokecolor_change}
                />
              </div>
              <div
                id="imageeditor"
                style={{ display: this.state.display_imageEditor }}
              >
                  <button
                    className="btn"
                    id="bring-to-front"
                    title="Bring to Front"
                    onClick={this.upward}
                  >
                    <ArrowUpwardIcon />
                  </button>
                  <button
                    className="btn"
                    id="send-to-back"
                    title="Send to Back"
                    onClick={this.downward}
                  >
                    <ArrowDownwardIcon />
                  </button>
                  <button
                    id="flip"
                    type="button"
                    className="btn"
                    title="Show Back View"
                    onClick={this.flip}
                  >
                    <FlipIcon />
                  </button>
                  <button
                    id="remove-selected"
                    className="btn"
                    title="Delete selected item"
                    onClick={this.delete_selected}
                  >
                    <DeleteIcon />
                  </button>
              </div>
            </div>
          </div>
        
        <div
          id="shirtDiv"
          className="page"
          style={{
            width: '530px',
            height: '630px',
            position: 'relative',
            backgroundColor: this.state.color,
          }}>
          <img id="tshirtFacing" src="./Title_files/crew_front.png" />
          <div
            id="drawingArea"
            onMouseEnter={this.onMouseEnter}
            onMouseLeave={this.onMouseLeave}
            style={{
              top: '100px',
              left: '160px',
              width: '200px',
              height: '400px',
              zIndex: 10,
              position: 'absolute',
            }}>
            <canvas
              id="tcanvas"
              width="200"
              height="400"
              className="hover"
              style={{ WebkitUserSelect: 'none' }}
            />
          </div>
        </div>
        </div>
      </div>
    );
  }
}
